package com.sharp;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.CanReadFileFilter;
import org.apache.commons.io.filefilter.FalseFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.lang3.StringUtils;

public class DesttopCleanupMain
{
	private static String extensions = "";
	
	private static String format = "yyyy-MM";
	
	private static SimpleDateFormat DTformat = new SimpleDateFormat();
	
	public static void main(String[] args) throws IOException
	{
		if(args != null && args.length >= 1){
			extensions = args[0];
			if(args.length == 2){
				List<String> validExtensions = Arrays.asList("yyyy-MM","yyyy-MM-dd");
				if(validExtensions.contains(args[1])){
					format = args[1];
				}else{
					throw new RuntimeException("日期格式参数不合法,请输入yyyy-MM或yyyy-MM-dd");
				}
			}
		}
		DTformat.applyPattern(format);
		String dir = URLDecoder.decode(System.getProperty("user.dir"),"UTF-8");;
//		String dir = "E:/dir/hello";
		File cleanDir = new File(dir).getParentFile();
		System.out.println("正在整理文件夹["+URLDecoder.decode(cleanDir.getAbsolutePath(),"UTF-8")+"]...");
		Collection<File> files = FileUtils.listFilesAndDirs(cleanDir, new SuffixFileFilter(extensions), StringUtils.isEmpty(extensions)?CanReadFileFilter.CAN_READ:FalseFileFilter.FALSE);
		for(File file : files)
		{
			if(file.canRead() && StringUtils.equalsIgnoreCase(file.getParent(), cleanDir.getPath())
					&& !StringUtils.equals(dir,URLDecoder.decode(file.getAbsolutePath(),"UTF-8"))){
				long lastModified = file.lastModified();
				File destDir = mkdir(new Date(lastModified),cleanDir.getAbsolutePath());
				File destFile = new File(destDir, file.getName());
				destFile.setLastModified(lastModified);
				if(file.isDirectory()){
					FileUtils.copyDirectory(file, destFile);
					FileUtils.deleteDirectory(file);
				}else{
					FileUtils.copyFile(file, destFile);	
					FileUtils.forceDelete(file);
				}
			}
		}
	}
	
	
	public static File mkdir(Date date, String dir)
	{
		String destDir = DTformat.format(date);
		File file = new File(dir,destDir);
		if(!file.exists()){
			file.mkdir();
		}
		return file;
	}
}
